package controller

import (
	"net"
	"net/http"
	"stock/global"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type Common struct {
	global.Comm
}

func (s Common) P(c *gin.Context) global.PageSort {
	var page global.PageSort
	c.ShouldBindBodyWith(&page, binding.JSON)

	if page.Sortfield == "" {
		page.Sortfield = "id"
	}
	if page.Sort == "" {
		page.Sort = "DESC"
	}
	if page.Limit <= 0 {
		page.Limit = 10
	}
	if page.Page <= 0 {
		page.Page = 1
	}
	page.Page = (page.Page - 1) * page.Limit
	return page
}

func GetClientIP(r *http.Request) string {
	xForwardedFor := r.Header.Get("X-Forwarded-For")
	if index := strings.Index(xForwardedFor, ", "); index >= 0 {
		return strings.TrimSpace(xForwardedFor[:index])
	}
	if xForwardedFor != "" {
		return xForwardedFor
	}

	xRealIP := r.Header.Get("X-Real-IP")
	if xRealIP != "" {
		return xRealIP
	}

	if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
		return ip
	}
	return r.RemoteAddr
}

func (c Common) Success(data interface{}, lang string, msg string, unmsg string, code int, context *gin.Context) {

	if code == 0 {
		code = http.StatusOK
	}
	context.JSON(http.StatusOK, gin.H{
		"code":  code,
		"data":  data,
		"lang":  lang,
		"msg":   msg,
		"unmsg": unmsg,
	})
	return
}

func (c Common) Fail(msg string, unmsg string, code int, lang string, context *gin.Context) {

	if code == 0 {
		code = 500
	}
	context.JSON(http.StatusOK, gin.H{
		"code":  code,
		"data":  "",
		"lang":  lang,
		"msg":   msg,
		"unmsg": unmsg,
	})
	return
}
